package com.jin.service;

import com.jin.Exception.http.NotFoundException;
import com.jin.Exception.http.ParameterException;
import com.jin.core.enumeration.CouponStatus;
import com.jin.model.Activity;
import com.jin.model.Coupon;
import com.jin.model.UserCoupon;
import com.jin.repository.ActivityRepository;
import com.jin.repository.CouponRepository;
import com.jin.repository.UserCouponRepository;
import com.jin.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CouponService {
    @Autowired
    CouponRepository couponRepository;
    @Autowired
    ActivityRepository activityRepository;
    @Autowired
    UserCouponRepository userCouponRepository;
    public List<Coupon> getByCategory(Long cid){
        Date date = new Date();
        return couponRepository.findByCategory(cid,date);
    }

    public List<Coupon> getWholeStoreCoupon(){
        Date date = new Date();
        return couponRepository.findByWholeStore(true,date);
    }

    public List<Coupon> getMyAvailableCoupons(Long uid){
        Date now = new Date();
        return couponRepository.findMyAvailable(uid,now);
    }

    public List<Coupon> getMyUsedCoupons(Long uid){
        Date now = new Date();
        return couponRepository.findMyUsed(uid,now);
    }

    public List<Coupon> getMyExpiredCoupons(Long uid){
        Date now = new Date();
        return couponRepository.findMyExpired(uid,now);
    }

    //用户领取优惠券
    public void collectOneCoupon(Long uid,Long couponId){
        //去数据库中查看优惠券是否存在，没有就抛出异常
        couponRepository
                .findById(couponId)
                .orElseThrow(()->new NotFoundException(40003));
        //看在活动里面有没有对应的coupon
        Activity activity = activityRepository
                .findByCouponListId(couponId)
                .orElseThrow(()->new NotFoundException(40010));
        //判断活动是否过期
        Date now = new Date();
        //时间比较的方法
        Boolean isIn = CommonUtil.isInTimeLine(now, activity.getStartTime(), activity.getEndTime());
        if (!isIn){
            throw new ParameterException(40006);
        }
        //看你是不是已经领取了
        userCouponRepository
                .findFirstByUserIdAndCouponId(uid,couponId)
                //已经领取抛出异常k
                .ifPresent((uc)->{throw new ParameterException(40006);});

        //多对多的记录添加，important,一般是添加到模型中在保存到数据库
        UserCoupon userCouponNew = UserCoupon.builder()
                .userId(uid)
                .couponId(couponId)
                .status(CouponStatus.AVAILABLE.getValue())
                .createTime(now)
                .build();
        //写入到数据库
        userCouponRepository.save(userCouponNew);
    }

}
